Page({
  data: {
    dateLayerVisible: false,
    houseLayerVisible: false,
    houseList: [],
    houseInfo: '', // 选择报修的房屋信息
    currentDate: new Date().getTime(),
    maxDate: Date.now() + 3 * 24 * 60 * 60 * 1000,

    houseId: '',
    name: '',
    gender: 1,
    mobile: '',
    visitDate: '', // 访问日期:3天以内的日期
  },

  onLoad() {
    this.getHouseList()
  },

  async getHouseList() {
    const { code, data: houseList } = await wx.http.get('/house')
    if (code !== 10000) return wx.utils.toast('获取房屋失败')
    this.setData({
      houseList,
    })
  },

  // 1. 选择要保修的房屋
  selectHouse(e) {
    const { name: houseInfo, id: houseId } = e.detail
    this.setData({
      houseInfo,
      houseId,
    })
  },

  // 2. 选择访问日期
  selectVisitDate(e) {
    this.setData({
      visitDate: wx.utils.formatDate(e.detail),
      dateLayerVisible: false,
    })
  },

  // 3. 去通行证页面
  async goPassport() {
    const { houseId, name, gender, mobile, visitDate } = this.data
    // 3.1 校验
    if (!wx.verify.verifyHouse(houseId)) return
    if (!wx.verify.verifyName(name)) return
    if (!wx.verify.verifyMobile(mobile)) return
    if (!wx.verify.verifyDate(visitDate)) return
    // 3.2 调接口
    const { code, data } = await wx.http.post('/visitor', { houseId, name, gender, mobile, visitDate })
    if (code !== 10000) return wx.utils.toast('填写访客信息失败')
    // 3.3 去通行证页面
    wx.reLaunch({
      url: '/visitor_pkg/pages/passport/index?id=' + data.id,
    })
  },

  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
})
